package com.tech.platform.cms.databases.mybatis.sqlParser.tenantParser.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.tech.platform.cms.databases.mybatis.sqlParser.handler.AbstractDynamicTableHandler;
import com.tech.platform.cms.databases.mybatis.sqlParser.tenantParser.TenantContext;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.ibatis.reflection.MetaObject;

import java.util.List;

/**
 * @author shengqiang.wu
 * @date 2019/12/31/031 15:37
 * @desc
 */
@Setter
@Accessors(chain = true)
public class NewTenantTableHandler extends AbstractDynamicTableHandler{

    private List<String> filterTables;

    @Override
    public String fetAppendTablePart() {
        String tenant = TenantContext.threadLocal.get();
        if(StrUtil.isEmpty(tenant)){
//            throw ExceptionUtils.mpe("use tenant strategy,get tenant info error,tenant is null");
            return "test";
        }
        return tenant;
    }

    @Override
    public boolean doFilterTable(String tableName) {
        if(CollUtil.isEmpty(filterTables)){
            return false;
        }

        for (String table : filterTables){
            if(StrUtil.equals(table,tableName)){
                return true;
            }
        }
        return false;
    }

    @Override
    public String dynamicTableName(MetaObject metaObject, String sql, String tableName) {
        if(doFilterTable(tableName)){
            return tableName;
        }
        return tableName+"_"+fetAppendTablePart();
    }
}
